#!/usr/bin/env node

/*
 * asn1extract - extract data at any position from ASN.1 structured data
 *
 * Copyright (c) 2015-2016 Kenji Urushima (kenji.urushima@gmail.com)
 *
 * This software is licensed under the terms of the MIT License.
 * https://kjur.github.io/jsrsasign/license
 *
 * The above copyright and license notice shall be 
 * included in all copies or substantial portions of the Software.
 * 
 * Please use '-h' option for this script usage.
 * ---------------------------------------------------------
 * DESCRIPTION
 *   This script extracts descendant ASN.1 structure data from ASN.1 
 *   DER data file by specifying index list in the ASN.1 nested
 *   structures.
 *
 * USAGE
 *   % asn1extract out.der z.req 0 0 0 0 1
 *   idx = 42
 *   04147ae13ee8a0c42a2cb428cbe7a605461940e2a1e9
 *   OCTETSTRING 7ae13ee8a0c42a2cb428cbe7a605461940e2a1e9
 *   # write this to out.der. "z.req" is OCSP request.
 */

var program = require('commander');
var rs = require('jsrsasign');
var rsu = require('jsrsasign-util');
var path = require('path');

program
  .version('1.0.1 (2016-Sep-11)')
  .description('extract arbitrary part of ASN.1 DER data by a list of position')
  .usage('[options] <new extracted file> <ASN.1 DER file> <idx1 idx2...>')
  .option('-a, --alltlv', 'extract whole ASN.1 TLV structure ')
  .option('-v, --vonly', 'extract ASN.1 V value only')
  .parse(process.argv);

if (program.args.length < 3)
  throw "wrong number of arguments";

var outFile = program.args[0];
var inFile = program.args[1];

var hex;
try {
  hex = rsu.readFileHexByBin(inFile);
} catch(ex) {
  throw "can't read file: " + inFile;
}

var idxList = program.args.slice(2);
//console.log("idxList = %j", idxList);
var parseInt10 = function(i) {return parseInt(i, 10);};
var idxList2 = idxList.map(parseInt10);
//console.log("idxList2 = %j", idxList2);

var idx = rs.ASN1HEX.getIdxbyList(hex, 0, idxList2);
console.log("idx = %j", idx);
var hExtract = rs.ASN1HEX.getTLV(hex, idx);
console.log(hExtract);
console.log(rs.ASN1HEX.dump(hExtract));
rsu.saveFileBinByHex(outFile, hExtract);

